﻿using System.Diagnostics;
using System.IO;
using System.Activities;
using Reactor.Workflow.Activities;

namespace Reactor.ServiceGrid.Workflows.Activities
{

    public sealed class UninstallAsWindowsService : ReactorCodeActivityBase
    {
        [RequiredArgument]
        public InArgument<string> TargetServiceInstallPath { get; set; }

        protected override void Execute(CodeActivityContext context)
        {
            const string reactorServicehostExe = "Reactor.ServiceHost.exe";
            var svcInstallDirectory = context.GetValue(TargetServiceInstallPath);

            if(!Directory.Exists(svcInstallDirectory))
                Log.WarnFormat("Unable to uninstall Windows Service because Reactor Service install directory not found at: {0}", svcInstallDirectory);

            var executable = Path.Combine(svcInstallDirectory, reactorServicehostExe);
            if (!File.Exists(executable))
                Log.WarnFormat(string.Format("Unable to uninstall Windows Service because Reactor Service executable not found at: {0}", svcInstallDirectory));
            else
            {
                if(Log.IsDebugEnabled) Log.DebugFormat("Attempting to uninstall windows service using the command: '{0} -u'", executable);
                Process.Start(executable, "-u");
            }
        }
    }
}
